var express = require('express');
var router = express.Router();
var fs   = require("fs");
var formidable=require('formidable');
var cacheFolder = 'public/RunData/';
var clientFolder='/RunData/';
/* GET home page. */
router.post('/', function(req, res, next) {
    var currentUser ='wy';
    var userDirPath =cacheFolder+'hybz';
       clientFolder=clientFolder+'hybz';
    if (!fs.existsSync(userDirPath)) {
        fs.mkdirSync(userDirPath);
    }
    var form = new formidable.IncomingForm(); 
    form.encoding = 'utf-8'; 
    form.uploadDir = userDirPath; 
    form.keepExtensions = true; 
    form.maxFieldsSize = 2 * 1024 * 1024; 
    form.type = true;
    var displayUrl;
    form.parse(req, function(err, fields, files) {
        if (err) {
            res.send(err);
            return;
        }
        var extName = ''; 
        switch (files.file.type) {
            case 'image/pjpeg':
                extName = 'jpg';
                break;
            case 'image/jpeg':
                extName = 'jpg';
                break;
            case 'image/png':
                extName = 'png';
                break;
            case 'image/x-png':
                extName = 'png';
                break;
        }
        if (extName.length === 0) {
            res.send({
                code: 202,
                msg: '请上传正确的格式（jpg/png）的图片'
            });
            return;
        } else {
            var avatarName = '/' + Date.now() + '.' + extName;//重命名
            var newPath = form.uploadDir + avatarName;
            displayUrl =clientFolder + avatarName;
            fs.renameSync(files.file.path, newPath); 
            res.send({
                code: 200,
                msg: displayUrl
            });
        }
    });

});

module.exports = router;
